package com.example.gameex2;

import org.Game.GameState;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;


public class GameView extends SurfaceView implements SurfaceHolder.Callback
{
	private GameViewThread m_thread;
	private SoundManager m_soundManager;
	private IState m_state;
	private Display m_display;
	
	public GameView(Context context) {
		super(context);
		
		setFocusable(true);
		
		AppManager.getInstance().SetGameView(this);
		AppManager.getInstance().SetResources(getResources());
		
		SoundManager.getInstance().Init(context);
		SoundManager.getInstance().addSound(1, R.raw.effect1);
		getHolder().addCallback(this);
		m_thread = new GameViewThread(getHolder(), this);
		
		//m_display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
		ChangeGameState(new GameState());
		// TODO Auto-generated constructor stub
	}
//	
	public void Update()
	{
		m_state.Update();
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		SoundManager.getInstance().play(1);
		return m_state.OnTouchEvent(event);
	}
	
	public void Render(Canvas canvas)
	{
		canvas.drawColor((Color.BLACK));
		m_state.Render(canvas);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		return m_state.OnKeyDown(keyCode, event);
	}
	
	public void ChangeGameState(IState _state)
	{
		if(m_state != null)
		{
			m_state.Destroy();
		}
		_state.Init();
		m_state = _state;
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		m_thread.setRunning(true);
		m_thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		boolean retry = true;
		m_thread.setRunning(false);
		
		while(retry)
		{
			try {
				m_thread.join();
				retry = false;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
